import FormText from './FormText';
import FormTextarea from './FormTextarea';
import FormNumber from './FormNumber';
import FormSelect from './FormSelect';
import FormCode from './FormCode';
import FormAttachment from './FormAttachment';
import FormUser from './FormUser';
import FormDate from './FormDate';
import FormDatetime from './FormDatetime';
import FormPlantime from './FormPlantime';
import FormPlanStartTime from './FormPlanStartTime';
import FormPlanEndTime from './FormPlanEndTime';
import FormPhone from './FormPhone';
import FormEmail from './FormEmail';
import FormSeparator from './FormSeparator';

import FormTaskNo from './FormTaskNo';

import FormAddress from './FormAddress';
import FormLocation from './FormLocation';
import FormInfo from './FormInfo';
import FormCascader from './FormCascader';
import FormCustomer from './FormCustomer';
import FormRelation from './FormRelation';
import FormRelatedTask from './FormRelatedTask';
import FormRelatedCustomers from './FormRelatedCustomers';
import FormSubServiceProvider from './FormSubServiceProvider'

import FormAutograph from './FormAutograph'
import FormSparepart from './FormSparepart'
import FormServiceIterm from './FormServiceIterm'
import FormMaterialReturn from './FormMaterialReturn'
import FormMaterialVerifyEliminate from './FormMaterialVerifyEliminate'
import FormServiceFailure from './FormServiceFailure'

import FormFormula from './FormFormula/index.ts';
import FormStyle from './FormStyle/index.ts';
import FormQualityRuleField from './FormQualityRuleField';
import FormQualityInfoField from './FormQualityInfoField';
import FormQualityField from './FormQualityField';
import FormGroup from './FormGroup/index.ts'

import FormRelatedCatalog from './FormRelatedCatalog';
import FormLogistics from './FormLogistics';

import { isCalendar, isEventCalendar} from '@src/util/CalendarUtil';
import FormRichTextField from './FormRichText';
import FormSubProduct from './FormSubProduct';
import FormLinkman from './FormLinkman';
import FormCustomerAddress from './FormCustomerAddress';
import FormCustomerLevel from './FormCustomerLevel'
import FormFaultLibrary from './FormFaultLibrary';

import FormSubSparePart from './FormSubSparePart';
import FormSubForm from './FormSubForm';
// 大概的看了一下，这个组件应该是废弃了，使用form-address组件
import FormProductCompleteAddress from './FormProductCompleteAddress'
import FormSubSucCase from './FormSubSucCase';
import FormLabel from './FormLabel';
import FormImage from './FormImage'
import FormServiceProviderQualification from './FormServiceProviderQualification';
import FormEngineerQualification from './FormEngineerQualification';
import FormSubRelationForm from './FormSubRelationForm';

import FormSubServiceItem from './FormSubServiceItem';

import FormMaterialsBill from './FormMaterialsBill';
// 物料-子表单
import FormSubMaterials from './FormSubMaterials'
import FormRelatedMaterial from './FormRelatedMaterial';
import FormIdentity from './FormIdentity'
import FormProductWarrantyService from './FormProductWarrantyService';

// 预计里程—工单回执
import FormEstimatedMileage from './FormEstimatedMileage';
// 预计里程—创建工单
import FormReckonEstimatedMileage from './FormEstimatedMileage/reckon.js';
// 实际里程—工单回执
import FormActualMileage from './FormActualMileage';
import FormProjectCustomer from './FormProjectCustomer';
import FormProjectProduct from './FormProjectProduct';
// 服务备注表单-产品
import FormRemarkProduct from './FormRemarkProduct'

// 连接器控件
import FormConnector from './FormConnector';
// 货币金额控件
import FormCurrency from './FormCurrency';
import FormCurrencyType from './FormCurrencyType';
import FormWorkHours from './FormWorkHours';

import FormStandardField from './FormStandard';

import FormRelatedServiceItem from './FormRelatedServiceItem';
// 备件返还
import FormSparePartsReturn from './FormSparePartsReturn';

// JS代码块
import FormJsControl from './FormJsControl';
// 部门
import FormTag from './FormTag';

import { getRootWindow } from '@src/util/dom'
import { isOpenLinkCardGray, isQualification, isNewFaultLibraryGray, haveCustomerLevelGray } from '@src/util/grayInfo';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
import { t } from '@src/locales';

// 所有字段
const ALL_FORM_FIELDS = [
  FormText,
  FormTextarea,
  FormNumber,
  FormSelect,
  FormCascader,
  FormCode,
  FormAttachment,
  FormUser,
  FormDate,
  FormDatetime,
  FormPlantime,
  FormPlanStartTime,
  FormPlanEndTime,
  FormPhone,
  FormEmail,
  FormTaskNo,
  FormSeparator,
  FormAddress,
  FormLocation,
  FormInfo,
  FormCustomer,
  FormAutograph,
  FormSparepart,
  FormServiceFailure,
  FormServiceIterm,
  FormMaterialReturn,
  FormMaterialVerifyEliminate,
  FormRelatedTask,
  FormRelatedCustomers,
  FormFormula,
  FormRelation,
  FormRelatedCatalog,
  FormStyle,
  FormQualityRuleField,
  FormQualityInfoField,
  FormQualityField,
  FormGroup,
  FormLogistics,
  FormRichTextField,
  FormSubProduct,
  FormLinkman,
  FormCustomerAddress,
  FormCustomerLevel,
  FormFaultLibrary,
  FormSubServiceProvider,
  FormServiceProviderQualification,
  FormEngineerQualification,
  FormSubSparePart,
  FormSubForm,
  FormProductCompleteAddress,
  FormMaterialsBill,
  FormSubMaterials,
  FormRelatedMaterial,
  FormSubRelationForm,
  FormSubSucCase,
  FormSubServiceItem,
  FormLabel,
  FormImage,
  FormConnector,
  FormIdentity,
  FormEstimatedMileage,
  FormActualMileage,
  FormReckonEstimatedMileage,
  FormProductWarrantyService,
  FormProjectCustomer,
  FormProjectProduct,
  FormRemarkProduct,
  FormCurrencyType,
  FormCurrency,
  FormWorkHours,
  FormStandardField,
  FormRelatedServiceItem,
  FormSparePartsReturn,
  FormJsControl,
  FormTag,
].reduce((acc, val) => (Array.isArray(val) ? acc = acc.concat(val) : acc.push(val)) && acc, []);

const FormFieldMap = {};
const PreviewComponents = {};
const SettingComponents = {};
const BuildComponents = {};
const ViewComponents = {};

for (let i = 0; i < ALL_FORM_FIELDS.length; i++) {
  let formField = ALL_FORM_FIELDS[i];

  let field = {
    name: formField.name, // 组件显示名称
    formType: formField.formType, // 组件类型
    fieldName: formField.fieldName, // 字段名，部分系统字段会提供
    isSystem: formField.isSystem || 0, // 是否为为系统组件
    alias: formField.alias,
    forceDelete: formField.forceDelete === true,
    // 组件标签
    label: formField.label,
    // 是否显示标题
    isShowDisplayName: formField.isShowDisplayName !== false,
    subFormFieldList: typeof formField.subFormFieldList === 'function' ? formField.subFormFieldList() : formField.subFormFieldList,
    isSystemControl: formField.isSystemControl,
    isSubForm: formField.isSubForm,
    setting: formField.setting || {}
  }

  // 里程帮助提示默认值
  if(['estimatedMileage', 'taskEstimatedMileage', 'actualMileage', 'remainTime', 'costTime', 'expectTime'].includes(formField.fieldName)){
    field.placeHolder = formField.placeHolder
    field.defaultSetting = formField.setting
  }


  if (!formField.alias) {
    // 预览组件
    field.previewIcon = formField.previewIcon;
    let previewComp = formField.component?.preview || {};
    PreviewComponents[previewComp.name] = previewComp;
    field.preview = previewComp.name; // 预览组件名

    // 设置组件
    let settingComp = formField.component?.setting;
    if (null != settingComp) {
      SettingComponents[settingComp.name] = settingComp;
      field.setting = settingComp.name; // 设置组件名
    }

    // 表单组件
    let buildComp = formField.component?.build;
    if (null != buildComp) {
      BuildComponents[buildComp.name] = buildComp;
      field.build = buildComp.name; // 表单组件名
    }

    // 显示组件
    let viewComp = formField.component?.view;
    if (null != viewComp) {
      ViewComponents[viewComp.name] = viewComp;
      field.view = viewComp.name
    }

    // 扩展组件
    let extendComp = formField.component?.extend;
    if (null != extendComp && Object.keys(extendComp).length > 0) {
      let extend = {};

      for (let name in extendComp) {
        let comp = extendComp[name];
        SettingComponents[comp.name] = comp;
        extend[name] = comp.name;
      }

      field.extend = extend;
    }
  }

  FormFieldMap[formField.formType] = field;
}

// 特殊的公共组件field js代码块目前只是在工单 工单回执 工单附件组件事件 事件回执、产品中存在
const SPECIAL_COMMON_FIELDS = ['jsCodeBlock']

const COMMON_FIELDS = ['text', 'textarea', 'number', 'select', 'cascader', 'attachment', 'user', 'date', 'datetime', 'phone', 'email', 'separator', 'address', 'location', 'info', 'autograph', 'related_task', 'formula','richtext'];
// 验证权限-添加额外控件
const role_auth = {
  task(){

    let fieldFormTypes = []

    if(internationalGray) {
      fieldFormTypes.push('currency')
    }

    if (isCalendar) {
      fieldFormTypes = fieldFormTypes.concat(['planStartTime', 'planEndTime'])
    }

    if (isOpenLinkCardGray()) {
      fieldFormTypes.push('connector')
    }

    fieldFormTypes.push(...SPECIAL_COMMON_FIELDS)

    return fieldFormTypes

  },
  taskReceipt() {

    let fieldFormTypes = []

    if(internationalGray) {
      fieldFormTypes = fieldFormTypes.concat(['currency', 'currencyType'])
    }

    if (isOpenLinkCardGray()) {
      fieldFormTypes.push('connector')
    }

    if(isNewFaultLibraryGray()){
      fieldFormTypes.push('newFaultLibrary')
    }

    fieldFormTypes.push(...SPECIAL_COMMON_FIELDS)

    return fieldFormTypes

  },
  event() {
    
    let fieldFormTypes = []
    
    if (isEventCalendar) {
      fieldFormTypes = fieldFormTypes.concat(['planStartTime', 'planEndTime'])
    }
    
    if (isOpenLinkCardGray()) {
      fieldFormTypes.push('connector')
    }

   fieldFormTypes.push(...SPECIAL_COMMON_FIELDS)
    
    return fieldFormTypes
  },
  eventReceipt() {
    
    let fieldFormTypes = []
    
    if (isOpenLinkCardGray()) {
      fieldFormTypes.push('connector')
    }

    fieldFormTypes.push(...SPECIAL_COMMON_FIELDS)
    
    return fieldFormTypes
  },
  customer() {
    
    let fieldFormTypes = []
    
    if (isOpenLinkCardGray()) {
      fieldFormTypes.push('connector')
    }

    const parentCustomerGray = haveCustomerLevelGray() || false

    if (parentCustomerGray){
      fieldFormTypes.push('parentCustomer')
    }

    fieldFormTypes.push(...SPECIAL_COMMON_FIELDS)
    
    return fieldFormTypes
  },
  product() {
    
    let fieldFormTypes = []
    
    if (isOpenLinkCardGray()) {
      fieldFormTypes.push('connector')
    }

    fieldFormTypes.push(...SPECIAL_COMMON_FIELDS)
    
    return fieldFormTypes
  },
  contract() {
    return internationalGray ? ['currency'] : [];
  },
};
function filterComponentByGrayInfo(arr){
  let bol1 = isQualification()
  if(bol1){
    let filterArr = ['authorizeTask', 'authorizeProduct', 'subCertifications']
    arr = arr.filter(item=>!filterArr.includes(item))
  }
  return arr
}
// 先在工单新建表单、工单回执表单增加连接器connector组件
const MODE_MANAGER = {
  base: {
    include: [...COMMON_FIELDS]
  },
  customer: {
    include: [
      ...COMMON_FIELDS,
      ...['related_customers','idcard'],
      ...role_auth.customer()
    ],
  },
  product: {
    include: [
      ...COMMON_FIELDS, 
      'productCompleteAddress', 
      'serviceProviders',
      ...role_auth.product(),
      'logistics', // 物流组件
    ],
  },
  task_card: {
    include: [...COMMON_FIELDS.filter(item=> !['richtext'].includes(item)), ...SPECIAL_COMMON_FIELDS],
  },
  event_card: {
    include: [ ...COMMON_FIELDS.filter(item=> !['richtext'].includes(item))]
  },
  product_menu: {
    include: [ ...COMMON_FIELDS]
  },
  product_register:{
    include: [
      ...COMMON_FIELDS.filter(item=> !['related_task', 'user', 'formula', 'separator', 'location', 'autograph','richtext'].includes(item)),
      ...['relationProduct'],
    ]
  },
  customer_card: {
    include: [
      ...COMMON_FIELDS.filter(item=> !['richtext'].includes(item)),
      ...['relationReplacementPart'],
    ]
  },
  // 工单表单
  task: {
    include: [
      ...COMMON_FIELDS,
      ...['relationCustomer', 'relationProduct', 'serviceProviders', 'level', 'serviceType', 'serviceContent', 'description', 'taskAttachment', 'richtext', 'faultLibrary', 'serviceProviderQualification', 'engineerQualification', 'relationForm', 'logistics', 'taskEstimatedMileage'],
      ...role_auth.task()

    ]
  },
  event: {
    include: [
      ...COMMON_FIELDS,
      ...['relationCustomer', 'relationProduct', 'level', 'logistics','relationForm'],
      ...role_auth.event() //  计划时间 or (计划开始时间 & 计划结束时间)
    ]
  },
  // 工单回执表单
  task_receipt: {
    include: [
      ...COMMON_FIELDS,
      ...['receiptAttachment', 'autograph', 'sparepart', 'serviceIterm', 'systemAutograph', 'materialReturn', 'materialVerifyEliminate', 'richtext', 'logistics', 'relationForm', 'estimatedMileage', 'actualMileage', 'sparePartsReturnExpense'],

      ...role_auth.taskReceipt()
    ]
  },
  eventReceipt: {
    include: [
      ...COMMON_FIELDS,
      ...['systemAutograph', 'logistics'],
      ...role_auth.eventReceipt()
    ]
  },
  remark: {
    include: [
      ...COMMON_FIELDS.filter(item => !['related_task'].includes(item)),
      'serviceRemark', // 服务备注
      'consultName', // 咨询分类
      'solveStatus', // 解决状态
      'remarkProduct', // 产品
    ]
  },
  contract: {
    include: [
      ...COMMON_FIELDS.filter(item => !['related_task'].includes(item)),
      ...['customer', 'customerAddress', 'linkman', 'product', 'subSparePart', 'subForm', 'productWarrantyService'],
      ...role_auth.contract()
    ]
  },
  service_provider: {
    include: [
      ...COMMON_FIELDS.filter(item => !['related_task'].includes(item)),
      ...filterComponentByGrayInfo(['provideQuality', 'authorizeTask', 'authorizeProduct', 'authorizeAddress', 'subSucCase', 'subCertifications', 'tagLabel', 'imageDisplay']),
    ]
  },
  service_engineer: {
    include: [
      ...COMMON_FIELDS.filter(item => !['related_task'].includes(item)),
      ...filterComponentByGrayInfo(['engineerQuality', 'authorizeTask', 'authorizeProduct', 'subSucCase', 'subCertifications']),
    ]
  },
  projectType: {
    include: [
      ...COMMON_FIELDS.filter(item => !['related_task'].includes(item)),
      ...['customerAddress', 'linkman', 'projectCustomer', 'projectProduct', 'planStartTime', 'planEndTime', 'connector']
    ]
  },
  projectTask: {
    include: [
      ...COMMON_FIELDS.filter(item => !['related_task'].includes(item)),
      ...['planStartTime', 'planEndTime', 'expectTime']
    ]
  },
  projectWorkLog: {
    include: [
      ...COMMON_FIELDS.filter(item => !['related_task', 'richtext'].includes(item)),
      ...['remainTime', 'costTime']
    ]
  },
  fault_library: {
    include: [
      ...COMMON_FIELDS.filter(item => !['idcard'].includes(item)),
      ...[ 'subSparePart', 'subMaterials', 'subServiceItem', 'knowledge']

    ]
  },

  findMode(mode, isShowRelationTask) {
    // 工单自定义节点（只支持能升级为公共表单的字段）
    if(isShowRelationTask){
      const baseInclude = MODE_MANAGER.base.include;
      const excludeItems = ['datetime', 'email', 'related_task', 'formula', 'richtext'];
      // 引用表单字段
      baseInclude.push('relationTask');
      // 工单自定义节点支持-连接器
      if (isOpenLinkCardGray()) {
        baseInclude.push('connector')
      }
      
      MODE_MANAGER.base.include = baseInclude.filter(item => !excludeItems.includes(item));
      return MODE_MANAGER.base;
    } 
    
    return MODE_MANAGER[mode] || MODE_MANAGER.base;
  }
}

/** 获取字段 */
FormFieldMap.get = function (formType) {

  let field = FormFieldMap[formType];
  if (field && field.alias) {
    let aliasField = FormFieldMap[field.alias];
    field.preview = aliasField.preview;
    field.setting = aliasField.setting;
    field.build = aliasField.build;
    field.extend = aliasField.extend || {};
  }

  return field;
}

const FieldManager = {
  /** 根据mode获取字段 */
  findModeFields(mode = 'base', isOpenQuality, isShowRelationTask) {
    let fields = ALL_FORM_FIELDS;
    let modeConfig = MODE_MANAGER.findMode(mode, isShowRelationTask);
    if(mode == 'task') {
      // 先默认不过滤掉质检字段，后面根据isOpenQuality来判断是否过滤
      modeConfig.include = [...modeConfig.include, 'quality']
    }
    let include = modeConfig.include || []
    
    // 排除字段
    if (include.length > 0) {
      fields = fields.filter(f => include.indexOf(f.formType) >= 0)
    }
    // 返回字段类型
    return fields.map(f => f.formType);
  },
  /** 根据字段类型获取单个字段 */
  findField(formType) {
    let field = FormFieldMap.get(formType);
    if (field && field.alias) {
      let aliasField = FormFieldMap[field.alias];

      field.preview = aliasField.preview;
      field.setting = aliasField.setting;
      field.build = aliasField.build;
      field.extend = aliasField.extend || {};
      field.previewIcon = aliasField.previewIcon

      return {
        ...aliasField,
        ...field
      };
    }

    return field;
  },
  // 生成付费标记
  generatePaidTags(field) {
    return {
      ...field,
      label: t('common.base.pay'),
      notOpened: true , // 没开通的控件(需要付费)
    }
  }
}

export {
  FieldManager,
  PreviewComponents,
  SettingComponents,
  BuildComponents,
  ViewComponents,
  FormFieldMap
}
